/**
 * 层序遍历，每遍历一个节点计数加一
 * @param {TreeNode} root
 * @return {number}
 */
const countNodes = root => {
  if (!root) return 0
  const queue = [root]
  let nodeNum = 0
  while (queue.length) {
    let len = queue.length

    for (let i = 0; i < len; i++) {
      const node = queue.shift()
      if (node) nodeNum += 1
      node.left && queue.push(node.left)
      node.right && queue.push(node.right)
    }
  }
  return nodeNum
}

const root = {
  val: 3,
  left: {
    val: 9,
    left: null,
    right: null
  },
  right: {
    val: 20,
    left: {
      val: 15,
      left: null,
      right: null
    },
    right: {
      val: 7,
      left: null,
      right: null
    }
  }
}

console.log(countNodes(root))